package com.orange.lswidget.widgets.event;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.widget.RemoteViews;

import com.orange.lswidget.R;
import com.orange.lswidget.widgets.event.entry.ConversationColumns;
import com.orange.lswidget.widgets.event.entry.MessageColumns;
import com.orange.lswidget.widgets.event.manager.EventManager;
import com.orange.lswidget.widgets.event.manager.MissCallManager;
import com.orange.lswidget.widgets.event.manager.UnreadMsgManager;
import com.orange.lswidget.widgets.event.manager.VoiceMailManager;
import com.orange.notificationsummary.utils.Constants;
import com.orange.notificationsummary.utils.Constants.EventType;
import com.orange.notificationsummary.utils.EventLSWidgetUtils;
import com.orange.util.LSEventUtils;
import com.orange.util.LogHelper;
import com.orange.util.VoiceMailUtils;

public class EventLSWidgetClient implements ConversationColumns,
		MessageColumns, EventType {
	private static final String		TAG								= "EventLSWidgetClient";
	private Context					mContext;

	private static final int		ACTIVITY_MISSED_CALL			= 1;
	private static final int		ACTIVITY_UNREAD_MESSAGE			= 2;
	private static final int		ACTIVITY_VOICE_MAIL				= 3;
	private static final int		ACTIVITY_NOTIFICATION_SCREEN	= -1;

	private MissCallManager			mMissCallManager;
	private UnreadMsgManager		mUnreadMsgManager;
	private VoiceMailManager		mVoiceMailManager;

	private EventCallBackInterface	mEventCallBackInterface;

	private boolean					mIsHaveContent					= true;
	private int						mEvent_newest_type				= -1;

	private int						missCallCount;
	private int						mUnreadMsgCount;
	private int						mVoiceMailCount;

	public EventLSWidgetClient(Context context) {
		mContext = context;
		mMissCallManager = MissCallManager.getInstance(context);
		mUnreadMsgManager = UnreadMsgManager.getInstance(context);
		mVoiceMailManager = VoiceMailManager.getInstance(context);
	}

	public void query(int type) {
		switch (type) {
		case MISSCALL_UPDATE:
			mMissCallManager.queryAllMissCallToList();
			break;
		case UNMSG_UPDATE:
			mUnreadMsgManager.queryAllUnreadMsgToList();
			break;
		case VVM_UPDATE:
			mVoiceMailManager.queryAllVoiceMailToList();
			break;
		case CONTACT_UPDATE:
		case ALL_UPDATE:
			mMissCallManager.queryAllMissCallToList();
			mUnreadMsgManager.queryAllUnreadMsgToList();
			mVoiceMailManager.queryAllVoiceMailToList();
			break;
		default:
			break;
		}
		startQueryForMessage();
	}

	private void startQueryForMessage() {
		RemoteViews remoteViews = new RemoteViews(LSEventUtils.sPackageName,
				R.layout.event);
		missCallCount = mMissCallManager.getCount();
		mUnreadMsgCount = mUnreadMsgManager.getCount();
		mVoiceMailCount = mVoiceMailManager.getCount();

		int sumCount = missCallCount + mUnreadMsgCount + mVoiceMailCount;
		// updateNotificationCount(sumCount);

		updateNotificationCount(sumCount, mUnreadMsgCount, missCallCount,
				mVoiceMailCount);

		boolean isPrivacy = EventLSWidgetUtils.getEventPreviewSetting(mContext);

		LogHelper.i(TAG, "startQueryForMessage. isPrivacy: " + isPrivacy
				+ " ,sumCount:" + sumCount + " ,voiceMailCount: "
				+ mVoiceMailCount + ", misscallCount: " + missCallCount
				+ ",unreadMessageCount: " + mUnreadMsgCount);

		if (sumCount > 1) {
			mIsHaveContent = true;
			remoteViews = getSummaryRemoteViews(remoteViews, false);
		} else if (sumCount == 1) {
			mIsHaveContent = true;
			if (!isPrivacy) {
				remoteViews = getDetailedRemoteViews(remoteViews);
			} else {
				remoteViews = getSummaryRemoteViews(remoteViews, true);
			}
		} else {
			mIsHaveContent = false;
		}

		updateLSWidgetProvider(remoteViews, mIsHaveContent);
	}

	/**
	 * @param remoteViews
	 * @param isDisplayTime
	 *            true indicates the time should be displayed, otherwise hidden.
	 * @return
	 */
	private RemoteViews getSummaryRemoteViews(RemoteViews remoteViews,
			boolean isDisplayTime) {
		RemoteViews tempRemoteViews = remoteViews;

		EventManager[] eventManagers = getRemoteViewsContent();
		LogHelper.i(TAG, "getSummaryRemoteViews. eventManagers: "
				+ eventManagers.length);
		if (eventManagers != null && eventManagers.length == 0) {
			mIsHaveContent = false;
			return tempRemoteViews;
		}

		LSEventUtils.sortEventInfo(eventManagers);
		setEventNewstType(eventManagers);

		RemoteViews basicRemoteViews = new RemoteViews(
				LSEventUtils.sPackageName, R.layout.layout_view_event_out_empty);
		basicRemoteViews.removeAllViews(R.id.layout_basic);

		for (EventManager manager : eventManagers) {
			LogHelper.i(
					TAG,
					"getSummaryRemoteViews. lastEventTime: "
							+ manager.getLastEventTime());
			if (manager.getLastEventTime() != 0) {
				RemoteViews eventInfoContentRemoteViews = new RemoteViews(
						LSEventUtils.sPackageName,
						R.layout.layout_view_event_out_basic_content);
				eventInfoContentRemoteViews = manager.getSummaryView(
						eventInfoContentRemoteViews, isDisplayTime);
				basicRemoteViews.addView(R.id.layout_basic,
						eventInfoContentRemoteViews);
			}
		}

		tempRemoteViews = basicRemoteViews;
		return tempRemoteViews;
	}

	private RemoteViews getDetailedRemoteViews(RemoteViews remoteViews) {
		if (1 == missCallCount) {
			LogHelper.v(TAG, "getDetailedRemoteViews. missCall");
			mMissCallManager.updateDetailedInfo();
			mMissCallManager.getDetailedView(remoteViews);
		} else if (1 == mUnreadMsgCount) {
			LogHelper.v(TAG, "getDetailedRemoteViews. unreadMsg");
			mUnreadMsgManager.updateDetailedInfo();
			mUnreadMsgManager.getDetailedView(remoteViews);
		} else if (1 == mVoiceMailCount) {
			LogHelper.v(TAG, "getDetailedRemoteViews. vvmCount");
			mVoiceMailManager.updateDetailedInfo();
			mVoiceMailManager.getDetailedView(remoteViews);
		}

		return remoteViews;
	}

	private EventManager[] getRemoteViewsContent() {
		List<EventManager> eventInfoList = new ArrayList<EventManager>();
		if (EventLSWidgetUtils.getNotifictionTypesIsChecked(mContext,
				Constants.KEY_WIDGET_EVENT_DETAIL_MISSED_CALL)
				&& mMissCallManager.getCount() != 0) {
			mMissCallManager.updateSummaryInfo();

			eventInfoList.add(mMissCallManager);
		}

		if (EventLSWidgetUtils.getNotifictionTypesIsChecked(mContext,
				Constants.KEY_WIDGET_EVENT_DETAIL_MESSAGE)
				&& mUnreadMsgManager.getCount() != 0) {
			mUnreadMsgManager.updateSummaryInfo();

			eventInfoList.add(mUnreadMsgManager);
		}

		if (EventLSWidgetUtils.getNotifictionTypesIsChecked(mContext,
				Constants.KEY_WIDGET_EVENT_DETAIL_VOICEMAIL)
				&& mVoiceMailManager.getCount() != 0) {
			mVoiceMailManager.updateSummaryInfo();

			eventInfoList.add(mVoiceMailManager);
		}

		EventManager[] eventInfos = eventInfoList
				.toArray(new EventManager[eventInfoList.size()]);
		return eventInfos;
	}

	private synchronized void setEventNewstType(EventManager[] eventInfos) {
		if (eventInfos != null && eventInfos.length > 0) {
			mEvent_newest_type = eventInfos[0].getEventType();
		}
	}

	private int getEventNewstType() {
		return mEvent_newest_type;
	}

	// add by gaoge 2011-08-19 for fix bug 0013239
	private void updateNotificationCount(int sumCount, int unreadmms_cnt,
			int miscall_cnt, int voicemail_cnt) {
		LSEventUtils.updateNotificationCount(mContext, sumCount, unreadmms_cnt,
				miscall_cnt, voicemail_cnt);
	}

	public void startNewActivity() {
		try {
			int eventType = getEventActivityType();

			switch (eventType) {
			case ACTIVITY_MISSED_CALL:
				mMissCallManager.startMissedCallActivity();
				// int missCallCount = mMissCallInfo.getCount();
				// int isOpenSecurityLock = Integer.parseInt(Settings.System
				// .getString(mContext.getContentResolver(),
				// Settings.System.LOCK_PATTERN_ENABLED));
				// if (isOpenSecurityLock == 1 && missCallCount == 1) {
				// RemoteViews eventInfoContentRemoteViews = new RemoteViews(
				// EventLSWidgetUtils.packageName,
				// R.layout.layout_view_event_out_empty);
				// mRemoteViews = eventInfoContentRemoteViews;
				// updateLSWidgetProvider(mIsHaveContent);
				// }
				break;
			case ACTIVITY_UNREAD_MESSAGE:
				mUnreadMsgManager.startUnreadMessageActivity();
				break;
			case ACTIVITY_VOICE_MAIL:
				VoiceMailUtils.startVoiceMailActivity(mContext);
				break;
			case ACTIVITY_NOTIFICATION_SCREEN:
				LSEventUtils.startNotificationSummary(mContext);
				break;
			default:
				break;
			}
		} catch (Exception e) {
		}
	}

	private int getEventActivityType() {
		int type = -10;

		int missCallCount = mMissCallManager.getCount();
		int unreadMessageCount = mUnreadMsgManager.getCount();
		int voiceMailCount = mVoiceMailManager.getCount();
		int sumCount = missCallCount + unreadMessageCount + voiceMailCount;
		if (sumCount > 0) {
			if (missCallCount == 0 && voiceMailCount == 0) {
				type = ACTIVITY_UNREAD_MESSAGE;
			} else if (unreadMessageCount == 0 && voiceMailCount == 0) {
				type = ACTIVITY_MISSED_CALL;
			} else if (missCallCount == 0 && unreadMessageCount == 0) {
				type = ACTIVITY_VOICE_MAIL;
			} else {
				boolean isNtfcExist = EventLSWidgetUtils.isPackageExist(
						mContext, Constants.PKG_NOTIFICATION_SUMMARY);
				boolean isNtfcEnabled = EventLSWidgetUtils
						.isNotificationScreenEnabled(mContext);
				if (isNtfcExist && isNtfcEnabled) {
					type = ACTIVITY_NOTIFICATION_SCREEN;
				} else {
					type = getLastEventActivityType();
				}
			}
		}

		return type;
	}

	private int getLastEventActivityType() {
		int activityType = ACTIVITY_NOTIFICATION_SCREEN;
		switch (getEventNewstType()) {
		case MISSCALL_UPDATE:
			activityType = ACTIVITY_MISSED_CALL;
			break;
		case UNMSG_UPDATE:
			activityType = ACTIVITY_UNREAD_MESSAGE;
			break;
		case VVM_UPDATE:
			activityType = ACTIVITY_VOICE_MAIL;
			break;
		default:
			break;
		}

		return activityType;
	}

	public void setEventCallBackInterface(
			EventCallBackInterface eventCallBackInterface) {
		mEventCallBackInterface = eventCallBackInterface;
	}

	private void updateLSWidgetProvider(RemoteViews remoteViews,
			boolean isHaveContent) {
		if (mEventCallBackInterface != null) {
			mEventCallBackInterface.onQueryComplete(remoteViews, isHaveContent);
		}
	}

	public interface EventCallBackInterface {
		void onQueryComplete(RemoteViews remoteViews, boolean isHaveContent);
	}

	// private void updateNotificationCount(int sumCount) {
	// if (sumCount > 0) {
	// LSEventUtils.updateNotificationCount(mContext,
	// EventManager.COLUMN_NOTIFICATION_COUNT, sumCount);
	// }
	// }
	// private boolean isLoad(int id) {// "date DESC"
	// boolean b = true;
	// Cursor c = null;
	// int pud_id = -1;
	// String selection = new String("thread_id='" + id + "'");
	// c = mContext.getContentResolver().query(
	// Uri.parse("content://mms/inbox"), null, selection, null, null);
	// if (c != null) {
	// if (c.moveToFirst()) {
	// pud_id = c.getInt(0);
	// }
	// }
	//
	// if (c != null) {
	// c.close();
	// }
	// if (pud_id != -1) {
	// b = MessagesDBHelper.isNotShowMMS(mContext, pud_id);
	// }
	// return b;
	//
	// }
}
